package com.xzx.study.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.xzx.study.db.BlackListDBHelper;
import com.xzx.study.po.BlackListInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xinzhixuan
 * @version V1.0
 * @date 2019/3/26 20:43
 */
public class BlackListDao {

    private static final String TAG = BlackListDao.class.getSimpleName();
    private BlackListDBHelper mBlackListDBHelper;

    public BlackListDao(BlackListDBHelper blackListDBHelper) {
        mBlackListDBHelper = blackListDBHelper;
    }

    public void add(BlackListInfo blackListInfo) {
        SQLiteDatabase database = mBlackListDBHelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put(BlackListDBHelper.BlackListTable.Columns.NUMBER, blackListInfo.getNumber());
        long id = database.insert(BlackListDBHelper.BlackListTable.TABLE_NAME, null, values);
        database.close();
        blackListInfo.setId(id);
        Log.i(TAG, "====插入成功：" + blackListInfo);
    }

    public void delete(long id) {
        SQLiteDatabase database = mBlackListDBHelper.getReadableDatabase();
        database.delete(BlackListDBHelper.BlackListTable.TABLE_NAME, BlackListDBHelper.BlackListTable.Columns.ID + "=?",
                        new String[]{id + ""});
        database.close();
        Log.i(TAG, "====删除成功：" + id);
    }

    public void update(BlackListInfo blackListInfo) {
        SQLiteDatabase database = mBlackListDBHelper.getReadableDatabase();
        ContentValues values = new ContentValues();
        values.put(BlackListDBHelper.BlackListTable.Columns.NUMBER, blackListInfo.getNumber());
        database.update(BlackListDBHelper.BlackListTable.TABLE_NAME, values,
                        BlackListDBHelper.BlackListTable.Columns.ID + "=?", new String[]{blackListInfo.getId() + ""});
        database.close();
        Log.i(TAG, "====更新成功：" + blackListInfo);
    }

    public List<BlackListInfo> getAll() {
        List<BlackListInfo> data = new ArrayList<>();
        SQLiteDatabase database = mBlackListDBHelper.getReadableDatabase();
        Cursor cursor = database.query(BlackListDBHelper.BlackListTable.TABLE_NAME, null, null, null, null, null,
                                        "_id desc");
        while (cursor.moveToNext()) {
            data.add(new BlackListInfo(cursor.getInt(0), cursor.getString(1)));
        }
        database.close();
        Log.i(TAG, "====查询成功：" + data);
        return data;
    }
}
